package com.ylx.excel.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.excel.dto.AppCapMobileDto;
import com.ylx.excel.mapper.AcAppCapMapper;
import com.ylx.excel.model.AcAppCap;
import com.ylx.excel.model.AcAppCapMobileAuth;
import com.ylx.excel.model.AcAppMobileAuth;
import com.ylx.excel.service.IAcAppCapService;
import com.ylx.mybatis.utils.SqlCreateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 能力信息表 服务实现类
 * </p>
 *
 * @author yanglixin
 * @since 2024-07-09
 */
@Slf4j
@Service
public class AcAppCapServiceImpl extends ServiceImpl<AcAppCapMapper, AcAppCap> implements IAcAppCapService {

    private static final List<String> needFilter = new ArrayList<>();
    private static final Set<String> appIds = new HashSet<>();

    static {
        //移动认证-扫码-一键登录
        needFilter.add("mobileAuthLoginScanCode");
        //移动认证-一键登录(IOS)
        needFilter.add("mobileAuthLoginIOS");
        //移动认证-一键登录(Android)
        needFilter.add("mobileAuthLoginAndroid");
        //移动认证-一键登录(Web/API)
        needFilter.add("mobileAuthLoginAPI");
        //三要素认证+安全基座(Android)
        needFilter.add("threeElementVerifyAndroid");
        //三要素认证+安全基座(IOS)
        needFilter.add("threeElementVerifyIOS");
        //三要素认证+安全基座(Web/API)
        needFilter.add("threeElementVerifyAPI");
        //可信认证H5
        needFilter.add("trustedAuthH5");
        //智能连接(掩码版扫码一键登录)
        needFilter.add("internalQrCode");

        //生产环境
        appIds.add("A0011001");
        appIds.add("A0012001");
        appIds.add("A0015001");
        appIds.add("A0022001");
        appIds.add("A0023001");
        appIds.add("A0024001");
        appIds.add("A0025001");
        appIds.add("A0026001");
        appIds.add("A0027001");
        appIds.add("A0028001");
        appIds.add("A0035001");
        appIds.add("A0041001");
        appIds.add("A0042001");
        appIds.add("A0043001");
        appIds.add("A0044001");
        appIds.add("A0119001");
        appIds.add("A0006007");
        appIds.add("A0132001");
        //测试环境
        //appIds.add("A0001018");
    }

    @Override
    public String deal() {
        LambdaQueryWrapper<AcAppCap> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AcAppCap::getDeleteFlag, 0);
        wrapper.in(AcAppCap::getCapType, needFilter);
        List<AcAppCap> capList = this.list(wrapper);
        Map<String, List<AcAppCap>> capGroupByAppId = capList.stream().collect(Collectors.groupingBy(AcAppCap::getAppId));

        List<AppCapMobileDto> appCapMobileDto = this.baseMapper.queryAppCapMobileData();
        Map<String, List<AppCapMobileDto>> groupByAppId = appCapMobileDto.stream()
                .filter(dto -> CharSequenceUtil.isNotBlank(dto.getAppId()))
                .collect(Collectors.groupingBy(AppCapMobileDto::getAppId));

        List<Long> needDeleteCapMobileAuthId = new ArrayList<>();
        List<Long> needDeleteMobileAuthId = new ArrayList<>();

        List<AcAppCap> capUpdateList = new ArrayList<>();
        List<AcAppCapMobileAuth> capMobileAuthUpdateList = new ArrayList<>();

        List<AcAppMobileAuth> mobileAuthUpdateList = new ArrayList<>();

        for (String appId : capGroupByAppId.keySet()) {
            //当前业务方的能力表
            List<AcAppCap> appCaps = capGroupByAppId.get(appId);
            //当前业务方的能力配置信息
            List<AppCapMobileDto> appCapMobileList = groupByAppId.get(appId);

            if (CollUtil.isEmpty(appCapMobileList)) {
                log.info("没有配置能力的appId: {}",appId);
                continue;
            }

            //找出重复的能力配置
            //能力配置
            Map<String, AppCapMobileDto> capSettingMap = new HashMap<>();
            for (AcAppCap cap : appCaps) {
                //当前能力的唯一标识
                String capType = cap.getCapType();
                for (AppCapMobileDto capMobileDto : appCapMobileList) {
                    //能力编码，平台，场景相同
                    if (CharSequenceUtil.equals(capMobileDto.getCapCode(), cap.getCapCode()) && Objects.equals(capMobileDto.getAppPlatformType(), cap.getAppPlatformType()) && CharSequenceUtil.equals(capMobileDto.getScene(), cap.getScene())) {
                        //找到了当前能力的配置  需要判断配置是否重复
                        //查看当前能力在之前是否已经找到过配置
                        AppCapMobileDto setting = capSettingMap.get(capType);
                        if (Objects.isNull(setting)) {
                            //之前没有找到配置放入当前配置
                            capSettingMap.put(capType, capMobileDto);

                        } else {
                            //之前有配置  取最新的一条配置留下删除原来的配置

                            if (capMobileDto.getId() > setting.getId()) {
                                //保留本次的，删除之前的
                                capSettingMap.put(capType, capMobileDto);
                                needDeleteCapMobileAuthId.add(setting.getId());
                                needDeleteMobileAuthId.add(setting.getMobileAuthId());
                            } else {
                                //删除本次的，保留之前的
                                capSettingMap.put(capType, setting);
                                needDeleteCapMobileAuthId.add(capMobileDto.getId());
                                needDeleteMobileAuthId.add(capMobileDto.getMobileAuthId());
                            }
                        }
                    }
                }
            }

            //当前业务方的能力信息回填正确的关联
            for (AcAppCap cap : appCaps) {
                String capType = cap.getCapType();
                //当前能力的配置信息
                AppCapMobileDto capSetting = capSettingMap.get(capType);
                if (Objects.isNull(capSetting)) {
                    //当前能力没有配置信息无需操作
                    continue;
                }
                AcAppCap capUpdate = new AcAppCap();
                AcAppCapMobileAuth capMobileAuthUpdate = new AcAppCapMobileAuth() ;

                //修改能力的sub_app_id和mobile_auth_app_id
                capUpdate.setId(cap.getId());
                capUpdate.setSubAppId(capSetting.getSubAppId());
                capUpdate.setMobileAuthAppId(capSetting.getMobileAuthAppId());
                //修改capMobileAuth的capId
                capMobileAuthUpdate.setId(capSetting.getId());
                capMobileAuthUpdate.setAcAppCapId(cap.getId());

                capUpdateList.add(capUpdate);
                capMobileAuthUpdateList.add(capMobileAuthUpdate);

                //修改配置
                if (appIds.contains(appId)) {
                    //ac_app_cap设置mobile_auth_app_id
                    //ac_app_mobile_auth设置appId和appKey和sub_app_id
                    //ac_app_cap_mobile_auth设置appSecret
                    AcAppMobileAuth appMobileAuthUpdate = new AcAppMobileAuth();
                    appMobileAuthUpdate.setId(capSetting.getMobileAuthId());
                    if (CharSequenceUtil.equals("mobileAuthLoginAndroid",capType)) {
                        //移动认证-一键登录(Android)
                        String thisCapAppId = "300012619569";
                        String thisCapAppKey = "10C5C81035117082776D60516151E112";
                        String thisCapSecret = "930DEAB770A0407098D6FA095FA007E9";

                        capUpdate.setMobileAuthAppId(thisCapAppId);

                        capMobileAuthUpdate.setAppSecret(thisCapSecret);

                        appMobileAuthUpdate.setMobileAuthAppId(thisCapAppId);
                        appMobileAuthUpdate.setMobileAuthAppKey(thisCapAppKey);
                        mobileAuthUpdateList.add(appMobileAuthUpdate);
                    }
                    if (CharSequenceUtil.equals("mobileAuthLoginIOS",capType)) {
                        //移动认证-一键登录(IOS)
                        String thisCapAppId = "300012619567";
                        String thisCapAppKey = "23D149FC13C01001BE21A60A3B0B0BB7";
                        String thisCapSecret = "23A0E966FB4449DCBF544EF466F84C4C";

                        capUpdate.setMobileAuthAppId(thisCapAppId);

                        capMobileAuthUpdate.setAppSecret(thisCapSecret);

                        appMobileAuthUpdate.setMobileAuthAppId(thisCapAppId);
                        appMobileAuthUpdate.setMobileAuthAppKey(thisCapAppKey);
                        mobileAuthUpdateList.add(appMobileAuthUpdate);
                    }
                    if (CharSequenceUtil.equals("mobileAuthLoginScanCode",capType)) {
                        //移动认证-扫码-一键登录
                        String thisCapAppId = "300012619566";
                        String thisCapAppKey = "00FBCB2E874F44F54A3A1740E4FF1C03";

                        capUpdate.setMobileAuthAppId(thisCapAppId);

                        appMobileAuthUpdate.setMobileAuthAppId(thisCapAppId);
                        appMobileAuthUpdate.setMobileAuthAppKey(thisCapAppKey);
                        mobileAuthUpdateList.add(appMobileAuthUpdate);
                    }
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        //生成删除语句
        stringBuilder.append("-- 删除ac_app_cap_mobile_auth的重复数据").append("\n");
        stringBuilder.append(SqlCreateUtil.deleteByIdListSql("ac_app_cap_mobile_auth","id",needDeleteCapMobileAuthId)).append("\n");
        stringBuilder.append("-- 删除ac_app_mobile_auth的重复数据").append("\n");
        stringBuilder.append(SqlCreateUtil.deleteByIdListSql("ac_app_mobile_auth","id",needDeleteMobileAuthId)).append("\n");

        //生成修改的语句
        stringBuilder.append("-- 修改cap的正确关联   且修改配置").append("\n");
        for (AcAppCap appCap : capUpdateList) {
            String updateByIdSql = SqlCreateUtil.updateByIdSql(appCap, "id");
            if (CharSequenceUtil.isNotBlank(updateByIdSql)) {
                stringBuilder.append(updateByIdSql).append("\n");
            }
        }

        stringBuilder.append("-- 修改capMobileAuth的正确关联  且修改配置").append("\n");
        for (AcAppCapMobileAuth capMobileAuth : capMobileAuthUpdateList) {
            String updateByIdSql = SqlCreateUtil.updateByIdSql(capMobileAuth, "id");
            if (CharSequenceUtil.isNotBlank(updateByIdSql)) {
                stringBuilder.append(updateByIdSql).append("\n");
            }
        }

        stringBuilder.append("-- 修改ac_app_mobile_auth配置").append("\n");
        for (AcAppMobileAuth mobileAuth : mobileAuthUpdateList) {
            String updateByIdSql = SqlCreateUtil.updateByIdSql(mobileAuth, "id");
            if (CharSequenceUtil.isNotBlank(updateByIdSql)) {
                stringBuilder.append(updateByIdSql).append("\n");
            }
        }

        return stringBuilder.toString();
    }
}
